import { effect } from "./effect"

interface Options {
    immediate?: boolean
    
}

// 转换函数 相等于深拷贝函数
const transform = (target: any, seen = new Set()) => {
    if (typeof target !== 'object' || target === null) return;
    if (seen.has(target)) {
        return target
    }
    seen.add(target)
    for (const key in target) {
        transform(target[key], seen)
    }
    return target
}

export const watch = (target: any, cb: Function, options ?: Options) => {
    let gutter: Function;
    // 将target 转换为函数
    if (typeof target === 'function') {
        gutter = target
    } else {
        gutter = () => transform(target)
    }
    // 处理回调
    let oldVal, newVal

    const run = ()=> {
        newVal = _effect()
        // 最新值发生变化时执行回调函数
        cb(oldVal, newVal)
        // 替换最新值为旧值，以便下次变化时使用
        oldVal = newVal
    }

    // 副作用函数
    const _effect = effect(gutter, {
        lazy: true,
        scheduler: run
    })
    // 立即执行
    if (options?.immediate) {
        run()
    } else {
        oldVal = _effect()
    }
}
